package com.lk.chat.connect;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/chat")

public class ChatConnect {
	
	private static List<Session> sessionList=new ArrayList<>();
	
	@OnOpen
	public void onOpen(Session session) throws IOException{
		sessionList.add(session);
		System.out.println("conect open!");
	}
	
	@OnClose
	public void onClose(CloseReason closeReason,Session session){
		sessionList.remove(session);
		System.out.println("connect closed!");
	}
	
	@OnError
	public void onError(Throwable t){
		System.out.println("connect error");
	}
	
	@OnMessage
	public void onMessage(Session session,String message){
		
			try {
				for(Session s: sessionList){
					s.getBasicRemote().sendText(message);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
}
